﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BMS.Syncro.Devices.Configuration.Entities;
using BMS.Syncro.Devices.Configuration.Interfaces;
using BMS.Syncro.Devices.Handler.Interfaces;
using BMS.Syncro.Devices.Message;
using BMS.Syncro.Devices.Persister.Interfaces;
using Common.Logging;

namespace BMS.Syncro.Devices.Handler
{
    public class DefaultVisitorSynchroHandler : IVisitorSynchroHandler
    {
        #region Properties
        private readonly ILog _log = null;
        public IConfiguration Configuration { get; set; }
        public ISyncroMessagePersister Persister { get; set; }
        #endregion Properties

        #region Methods
        public DefaultVisitorSynchroHandler()
        {
            _log = LogManager.GetLogger(this.GetType());
        }
        #endregion Methods

        #region IVisitorSynchroHandler Members

        public string ProcessName
        {
            get
            {
                return this.GetType().Name;
            }
        }

        /// <summary>
        /// Captures VisitorMessage from the MSMQ and persist it in the specific device
        /// </summary>
        /// <param name="visitorMessage"></param>
        public void Handler(VisitorMessage visitorMessage)
        {
            Configuration.LoadConfigurations();
            // Logger for the initial process
            _log.Info("Iniciando handler para el proceso de sincronización.");
            foreach (var config in Configuration.Configurations)
            {
                try
                {
                    SyncroMessage synchro = GetSyncroMessage(visitorMessage, config);
                    // Invoke the DefaultZKEMPersister
                    Persister.Save(synchro);
                    _log.Info("Sincronización finalizada.");
                }
                catch (Exception exc)
                {
                    _log.Error("Error realizando sincronización.", exc);
                    throw exc;

                }
            }
        }

        /// <summary>
        /// Get a synchro message for update the biometric device
        /// </summary>
        /// <param name="visitorMessage"></param>
        /// <param name="configuration"></param>
        /// <returns></returns>
        private SyncroMessage GetSyncroMessage(VisitorMessage visitorMessage, DeviceConfigurationEntity configuration)
        {
            return new SyncroMessage()
            {
                Action = Message.Entities.DeviceAction.Save,
                Visitor = visitorMessage,
                Device = new DeviceMessage()
                {
                    IpAddress = configuration.Ip,
                    Port = configuration.Port,
                    Name = configuration.Name
                }
            };
        }

        #endregion
    }
}
